package com.gx.security.digital_signature;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.Hex;

import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

/**
 * Created by gx on 2017/3/30.
 */
public class RSAsignatureTest {
    private static final String src = "imooc security signatureRSA";

    public static void main(String[] args) {
        jdkRSA();
    }
    public static void jdkRSA(){
        try {

            //初始化秘钥
            KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");

            //初始化长度
//            keyPairGenerator.initialize(512);
            keyPairGenerator.initialize(1024,new SecureRandom());

            KeyPair keyPair = keyPairGenerator.generateKeyPair();
            //公钥验证
            RSAPublicKey rsaPublicKey = (RSAPublicKey) keyPair.getPublic();
            //私钥签名
            RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) keyPair.getPrivate();
            System.out.println("Public Key:" + Base64.encodeBase64String(rsaPublicKey.getEncoded()));
            System.out.println("PrivateKey :" + Base64.encodeBase64String(rsaPrivateKey.getEncoded()));

            //执行签名
            PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(rsaPrivateKey.getEncoded());
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
            Signature signature = Signature.getInstance("MD5withRSA");
            signature.initSign(privateKey);
            //输入执行加密的内容
            signature.update(src.getBytes());
            //获得签名
            byte [] result  = signature.sign();
            System.out.println("JDK RSA sign 实现"+ Hex.encodeHexString(result));


            //验证签名
            X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(rsaPublicKey.getEncoded());
            keyFactory = KeyFactory.getInstance("RSA");
            PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);
            //得到签名
            signature = Signature.getInstance("MD5withRSA");
            signature.initVerify(publicKey);
            signature.update(src.getBytes());
            boolean bool = signature.verify(result);
            System.out.println("RSA 验证结果——-->"+bool);
        }catch (Exception e){
            e.printStackTrace();
            System.err.println(e.getMessage());
            System.err.println(e);
        }

    }

}
